package be.sc.classicnetwork.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import be.sc.classicnetwork.model.Request;
import be.sc.classicnetwork.service.GenericService;
import be.sc.classicnetwork.util.PropertiesUtils;
import freemarker.template.SimpleHash;

public class RequestFormController extends AbstractFormController {

    private static final String REQUEST_TEMPLATE = "request.ftl";

    private GenericService<Request> requestService;

    /**
     * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
     */
    @Override
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
	return new Request();
    }

    /**
     * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(java.lang.Object)
     */
    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
	    BindException errors) throws Exception {
	Request req = (Request) command;

	// save the request
	this.requestService.saveOrUpdate(req);

	// put the request info as model for freemarker template
	SimpleHash model = new SimpleHash();
	model.put("request", req);

	// get some application properties
	String from = PropertiesUtils.MAIL_FROM;
	String fromPersonal = PropertiesUtils.MAIL_FROM_PERSONAL;
	String subjectPrefix = PropertiesUtils.MAIL_SUBJECT_PREFIX;

	// send the email
	getServiceLocator().getMailService().sendFreeMarkerTemplate(from, fromPersonal, from,
		subjectPrefix + " Request: " + req.getSubject(), null, REQUEST_TEMPLATE, model);

	// show confirmation message
	return new ModelAndView("info", "text", "A representative of Classic Network will contact you very shortly");
    }

    public void setRequestService(GenericService<Request> requestService) {
	this.requestService = requestService;
    }

}
